package RPC;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.net.Socket;

public class RPCimporter<S> {
	
	@SuppressWarnings("unchecked")
	public S importer(final Class<?> serviceClass,final InetSocketAddress addr){
		return (S)Proxy.newProxyInstance(serviceClass.getClassLoader(), new Class<?>[]{serviceClass.getInterfaces()[0]}, new InvocationHandler() {
			@Override
			public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
				Socket socket = null;
				ObjectOutputStream out = null;
				ObjectInputStream ins = null;
				try{
					socket = new Socket();
					socket.connect(addr);
					out = new ObjectOutputStream(socket.getOutputStream());
					out.writeUTF(serviceClass.getName());
					out.writeUTF(method.getName());
					out.writeObject(method.getParameterTypes());
					out.writeObject(args);
					ins = new ObjectInputStream(socket.getInputStream());
					return ins.readObject();
				}finally {
					if(out != null)
						out.close();
					if(ins != null)
						ins.close();
					if(socket != null)
						socket.close();
				}
				
			}
		});
	}
}
